package com.pengzy.comment.mybatis.config.handel;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.pengzy.comment.core.current.CurrentOperatorHolder;
import com.pengzy.comment.core.current.ICurrentOperator;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充
 *
 * @author cui
 * @version 1.0
 * @date 2021-09-06
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        if (metaObject.hasGetter("createTime")) {
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
        if (metaObject.hasGetter("updateTime")) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }

        ICurrentOperator operator = CurrentOperatorHolder.get();
        if (operator != null && operator.getInfo()!=null) {
            if (metaObject.hasGetter("createById")) {
                this.strictInsertFill(metaObject, "createById", Long.class, operator.getInfo().getAccountId());
            }
            if (metaObject.hasGetter("createBy")) {
                this.strictInsertFill(metaObject, "createBy", String.class,  operator.getInfo().getName());
            }
            if (metaObject.hasGetter("updateById")) {
                this.strictInsertFill(metaObject, "updateById", Long.class, operator.getInfo().getAccountId());
            }
            if (metaObject.hasGetter("updateBy")) {
                this.strictInsertFill(metaObject, "updateBy", String.class,  operator.getInfo().getName());
            }
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        if (metaObject.hasGetter("updateTime")) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
        ICurrentOperator operator = CurrentOperatorHolder.get();
        if (operator != null && operator.getInfo()!=null) {
            if (metaObject.hasGetter("updateById")) {
                this.strictInsertFill(metaObject, "updateById", Long.class,  operator.getInfo().getAccountId());
            }
            if (metaObject.hasGetter("updateBy")) {
                this.strictInsertFill(metaObject, "updateBy", String.class,  operator.getInfo().getName());
            }
        }
    }

}
